

var app = new Vue({
	el: '#app',
	data() {
		return {
			isWeixin: true, // 是否微信
			timer: null, // 延时对象

			localData: [], // 数据缓存

			activeNames: [0],
			form: {
				id: '-1', // -1表示草稿
				title: `${Tools.switchTime(new Date(), 'yyyy-MM-dd')}项目费用`,
				total: '',
				typeList: [
					{
						name: '计费类目',
						total: '',
						children: [
							this.getCostItem()
						]
					}
				]
			},

			// 公式
			formula: [
				{code: 1, name: '长×宽', value: (row) => {
					let res = `${row.long}×${row.width}×${row.price}`;
					if(row.deduct?.length) {
						row.deduct.forEach(item => {
							res += `-${item.formulaText}`;
						});
					}
					return res;
				}},
				{code: 2, name: '(长+宽)×高', value: (row) => {
					let res = `(${row.long}+${row.width})×${row.height}×${row.price}`;
					if(row.deduct?.length) {
						row.deduct.forEach(item => {
							res += `-${item.formulaText}`;
						});
					}
					return res;
				}},
				{code: 99, name: '自定义', value: (row) => {
					return row.formulaText+'';
				}}
			],
			// 符号
			symbol: ['㎡', '×', '+', '-'],
			// 键盘
			keyboard: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.', '(', ')', '+', '-', '×', '÷'],

			// 当前时间
			currentTime: '',

			// 弹窗
			dialog: {
				v1: false,
				v2: false,
				title: '',
				message: '',
				confirm: null
			},
		}
	},
	// computed: {
	// 	formJson() {
	// 		return JSON.stringify(this.form);
	// 	}
	// },
	// watch: {
	// 	formJson: {
	// 		handler(newVal, oldVal) {
	// 			console.log('111111111');
	// 			// console.log(JSON.stringify(newVal))
	// 			// console.log(JSON.stringify(oldVal))
	// 			console.log(newVal == oldVal)
	// 			if(newVal != oldVal) {
	// 				this.watchCostChange();
	// 			}
	// 			// this.watchCostChange();
	// 		},
	// 		deep: true
	// 	}
	// },
	mounted() {
		this.isWeixin = Tools.getBrowserType() === 'Weixin';
		if(!this.isWeixin) {
			// 获取到缓存
			this.localData = Tools.LOCAL.get('formList') || [];
			// -1表示草稿
			let oForm = this.localData.find(item => item.id == -1);
			if(oForm) {
				this.form = oForm;
			}
		}
	},
	methods: {
		// 监听费用改变
		watchCostChange() {
			clearTimeout(this.timer);
			this.timer = setTimeout(() => {
				let form = JSON.parse(JSON.stringify(this.form));
				let aTotal = 0;
				for(let i = 0; i < form.typeList.length; i++) {
					let aItem = form.typeList[i];
					let bTotal = 0;
					for(let j = 0; j < aItem.children.length; j++) {
						let bItem = aItem.children[j];

						// 扣减项 ------------------
						for(let k = 0; k < bItem.deduct.length; k++) {
							let cItem = bItem.deduct[k];
							// 计算result
							let formula = this.formula.find(item => item.code == cItem.formula).value({...cItem, price: bItem.price});
							console.log('citem:'+formula);
							cItem.formulaText = formula;
							formula = formula.replace(/×/g, '*').replace(/÷/g, '\/');
							let result = '';
							try {
								eval(`window.costResult = ${formula}`);
								result = window.costResult.toFixed(3);
							} catch (e) {
								result = '';
							}
							cItem.result = result > 0 ? result : '';
						}
						console.log('bdeduct', bItem.deduct)

						// 计算result
						let formula = this.formula.find(item => item.code == bItem.formula).value(bItem);
						console.log('bitem:'+formula);
						bItem.formulaText = formula;
						formula = formula.replace(/×/g, '*').replace(/÷/g, '\/');;
						let result = '';
						try {
							eval(`window.costResult = ${formula}`);
							result = window.costResult.toFixed(3);
						} catch (e) {
							result = '';
						}
						bItem.result = result > 0 ? result : '';
						// 计算类目合计
						if(bItem.result) {
							bTotal += parseFloat(bItem.result);
						} else {
							bTotal = '';
							break;
						}
					}
					aItem.total = bTotal ? bTotal.toFixed(3) : '';
					// 计算项目合计
					if(aTotal !== '' && bTotal !== '') {
						aTotal += bTotal;
					} else {
						aTotal = '';
					}
				}
				form.total = aTotal ? aTotal.toFixed(3) : '';

				// 保存到缓存
				let index = this.localData.findIndex(item => item.id === form.id);
				if(index > -1) {
					this.localData.splice(index, 1, form);
				} else {
					this.localData.push(form);
				}
				Tools.LOCAL.set('formList', this.localData);
				// 更新form
				this.form = form;
				console.log(form);
			}, 50);
		},

		// 费用对象
		getCostItem() {
			return JSON.parse(JSON.stringify({ name: '', formula: 1, formulaText: '', long: '', width: '', height: '', price: '', deduct: [], result: '', edit: true }))
		},
		// 扣减项对象
		getDeductItem() {
			return JSON.parse(JSON.stringify({name: '', formula: 1, formulaText: '', long: '', width: '', height: '', result: ''}))
		},

		// -------------------------
		// 添加计费类目
		addTypeItem() {
			this.form.typeList.push({
				name: '计费类目',
				total: '',
				children: []
			})
			// 添加默认计费名称
			this.addCostItem(this.form.typeList[this.form.typeList.length - 1]);
			// 默认打开
			this.activeNames.push(this.form.typeList.length - 1);
			this.watchCostChange();
		},
		// 删除本类目
		deleteTypeItem(aIndex) {
			this.showDialog('此操作将删除该计费类目, 是否继续?', () => {
				this.form.typeList.splice(aIndex, 1);
				if (!this.form.typeList.length) {
					this.addTypeItem();
				}
				this.watchCostChange();
			})
		},

		// --------------------------
		// 添加计费名
		addCostItem(aItem) {
			aItem.children.push(this.getCostItem())
			this.watchCostChange();
		},
		// 修改计费名
		editCostItem(aItem, bItem) {
			bItem.edit = true;
			this.watchCostChange();
		},
		// 确定计费名
		saveCostItem(aIndex, bItem) {
			setTimeout(() => {
				if (!this.checkCost(aIndex, bItem)) {
					return;
				}
				bItem.edit = false;
				this.watchCostChange();
			}, 100);
		},
		// 删除计费名
		deleteCostItem(aItem, bIndex) {
			this.showDialog('此操作将删除该计费名称, 是否继续?', () => {
				aItem.children.splice(bIndex, 1);
				this.watchCostChange();
			})
		},
		// 验证计费名称
		checkCost(aIndex, bItem, returnMsg = false) {
			let aItem = this.form.typeList[aIndex];
			let msg = '';
			let deductMsg = ''; // 扣减消息
			if (!bItem.name.trim().length) {
				msg = `请输入 ${aIndex + 1}.${aItem.name} 的计费名称`;
			} else if(deductMsg = this.checkDeduct(aIndex, bItem)) {
				msg = deductMsg;
			} else if (!(Number(bItem.result) > 0)) {
				msg = `请调整 ${aIndex + 1}.${aItem.name} 的计费参数，计费结果需要大于0`;
			}
			if(returnMsg) {
				return msg;
			}
			if (msg) {
				this.$message({
					type: 'error',
					message: msg,
					duration: 5000
				})
			}
			return !msg;
		},
		// 修改公式类型
		changeFormula(bItem, code) {
			bItem.formula = code;
			if(code == 3) {
				bItem.formulaText = '';
			}
			this.watchCostChange();
		},
		// 键盘点击
		changeKeyboard(bItem, key, id) {
			let el = document.querySelector(`#${id}`);
			// 获取光标位置
			let pos = this.getPosition(el);
			// 设置内容
			let start = bItem.formulaText.slice(0, pos);
			let end = bItem.formulaText.slice(pos, bItem.formulaText.length);
			bItem.formulaText = start + key + end;
			// 设置光标位置
			this.setPosition(el, pos+1);
			// 执行改变
			this.watchCostChange();
		},
		// 获取光标位置
		getPosition(element) {
			let cursorPos = 0;
			if(document.selection) { // IE
				var selectRange = document.selection.createRange();
				selectRange.moveStart('character', -element.value.length);
				cursorPos = selectRange.text.length;
			} else if (element.selectionStart || element.selectionStart == '0') {
				cursorPos = element.selectionStart;
			}
			return cursorPos;
		},
		// 设置光标位置
		setPosition(el, pos) {
			if(el.setSelectionRange) {
				el.focus();
				setTimeout(() => {
					el.setSelectionRange(pos, pos);
				}, 0);
			} else if(el.createTextRange) { // ie
				var range = el.createTextRange();
				range.collapse(true);
				range.moveEnd('character', pos);
				range.moveStart('character', pos);
				range.select();
			}
		},
		// 扣减项---------
		// 添加扣减项
		addDeduct(bItem, code) {
			let oItem = this.getDeductItem();
			oItem.formula = code;
			bItem.deduct.push(oItem);
			this.watchCostChange();
		},
		// 删除扣减项
		deleteDeduct(bItem, cIndex) {
			bItem.deduct.splice(cIndex, 1);
			this.watchCostChange();
		},
		// 验证扣减项
		checkDeduct(aIndex, bItem) {
			let aItem = this.form.typeList[aIndex];
			let msg = '';
			for(let i = 0; i < bItem.deduct.length; i++) {
				let item = bItem.deduct[i];
				console.log(item);
				if(!item.name.length) {
					msg = `请输入 ${aIndex + 1}.${aItem.name} 的扣减项名称`;
					break;
				} else if([1, 2].includes(item.formula) && !(Number(item.long) > 0)) {
					msg = `请输入 ${aIndex + 1}.${aItem.name} 的扣减项长度`;
					break;
				} else if([1, 2].includes(item.formula) && !(Number(item.width) > 0)) {
					msg = `请输入 ${aIndex + 1}.${aItem.name} 的扣减项宽度`;
					break;
				} else if([2].includes(item.formula) && !(Number(item.height) > 0)) {
					msg = `请输入 ${aIndex + 1}.${aItem.name} 的扣减项高度`;
					break;
				} else if ([99].includes(item.formula) && !(Number(item.result) > 0)) {
					msg = `请输入 ${aIndex + 1}.${aItem.name} 的扣减项费用`;
					break;
				}
			}
			return msg;
		},

		// --------------------------
		// 保存为图片
		async saveToImage() {
			if(!this.checkProject()) {
				return;
			}
			this.currentTime = Tools.switchTime(new Date(), 'yyyy-MM-dd HH:mm:ss');
			await Tools.waitTimeout(100);
			html2canvas(this.$refs.imageWrapper).then(canvas => {
				const image = canvas.toDataURL('image/jpeg', 1.0);

				const a = document.createElement('a');
				a.href = image;
				a.download = this.form.title+'_'+(new Date().getTime())+'.png';
				document.body.appendChild(a);
				a.click();
				document.body.removeChild(a);
			})
		},
		// 清空本项目
		clearProject() {
			this.showDialog('此操作将清空本项目, 是否继续?', () => {
				this.form.title = `${Tools.switchTime(new Date(), 'yyyy-MM-dd')}项目费用`;
				this.form.total = '';
				this.form.typeList = [
					{
						name: '计费类目',
						total: '',
						children: [
							this.getCostItem()
						]
					}
				]
				// 默认打开
				this.activeNames = [0];
				this.watchCostChange();
			})
		},
		// 保存到列表
		saveToList() {

		},
		// 验证项目
		checkProject() {
			let msg = '';
			if(!this.form.title.length) {
				msg = '请输入项目名称';
			} else {
				typeForm:for(let i = 0; i < this.form.typeList.length; i++) {
					let item = this.form.typeList[i];
					if(!item.name.length) {
						msg = `请输入计费类目 ${i+1} 的名称`;
						break;
					}
					for(let j = 0; j < item.children.length; j++) {
						let child = item.children[j];
						let childMsg = this.checkCost(i, child, true);
						if(!childMsg && child.edit) {
							childMsg = `请确认 ${i + 1}.${item.name} 的 ${j + 1}.${child.name}`;
						}
						if(childMsg) {
							msg = childMsg;
							break typeForm;
						}
					}
				}
			}
			if (msg) {
				this.$message({
					type: 'error',
					message: msg,
					duration: 5000
				})
			}
			return !msg;
		},


		// 弹窗----------------------
		showDialog(message, confirm) {
			this.dialog.message = message;
			this.dialog.confirm = confirm;

			this.dialog.v1 = true;
			setTimeout(() => {
				this.dialog.v2 = true;
			}, 30);
		},
		dialogConfirm() {
			if (this.dialog.confirm) {
				this.dialog.confirm();
				this.dialogClose();
			}
		},
		dialogClose() {
			this.dialog.v2 = false;
			setTimeout(() => {
				this.dialog.v1 = false;
			}, 300);
		},
	}
})
